package com.clps.learning.utils;

import com.clps.learning.pojo.BaseUser;

import java.io.*;

/**
 * @Program: clps-learning
 * @Description:
 * @author: Cooper
 * @date: 2021.10.12
 * @Version: 1.0
 */
public class FileUtil {

    public static Boolean write(BaseUser baseUser) {
        // resources路径
        String filePath = FileUtil.class.getClassLoader().getResource("").getPath() + baseUser.getUsername() + ".txt";

        // 序列化user对象并写出txt文件
        try (
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(baseUser);
            oos.flush();
            return true;
        }catch (IOException e){
            return false;
        }
    }


    public static BaseUser read(String username)  {
        // resources路径
        String filePath = FileUtil.class.getClassLoader().getResource("").getPath() + username + ".txt";
        try(
            // 反序列化
            FileInputStream fis = new FileInputStream(new File(filePath));
            ObjectInputStream ois = new ObjectInputStream(fis);
        ){
            BaseUser baseUser = (BaseUser) ois.readObject();
            return baseUser;
        }catch (Exception e){
            return null;
        }
    }

}
